package com.myproject.myblogserver.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myproject.myblogserver.contant.CommonConstants;
import com.myproject.myblogserver.dto.PageResultDto;
import com.myproject.myblogserver.dto.blog.BlogPreviewDto;
import com.myproject.myblogserver.dto.favoriteFolder.FavoriteFolderAddDto;
import com.myproject.myblogserver.dto.favoriteFolder.FavoriteFolderDetailDto;
import com.myproject.myblogserver.dto.favoriteFolder.FavoriteFolderPreviewDto;
import com.myproject.myblogserver.entity.Blog;
import com.myproject.myblogserver.entity.FavoriteFolder;
import com.myproject.myblogserver.entity.FolderBlog;
import com.myproject.myblogserver.service.IBlogService;
import com.myproject.myblogserver.service.IFavoriteFolderService;
import com.myproject.myblogserver.service.IFolderBlogService;
import com.myproject.myblogserver.utils.JwtUtil;

/**
 * <p>
 * 收藏夹表 前端控制器
 * </p>
 *
 * @author jiangweike
 * @since 2025-02-16
 */
@Controller
@RequestMapping("/favoriteFolder")
public class FavoriteFolderController {

    @Autowired
    private IFavoriteFolderService favoriteFolderService;

    @Autowired
    private IFolderBlogService folderBlogService;

    @Autowired
    private IBlogService blogService;

    @PostMapping("/add")
    public ResponseEntity<?> add(@RequestBody FavoriteFolderAddDto favoriteFolderAddDto,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 检查是否已存在同名收藏夹
            var existingFolder = favoriteFolderService.lambdaQuery()
                    .eq(FavoriteFolder::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(FavoriteFolder::getUserId, userId)
                    .eq(FavoriteFolder::getName, favoriteFolderAddDto.getName())
                    .one();

            if (existingFolder != null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("已存在同名收藏夹！");
            }

            // 创建新收藏夹
            var favoriteFolder = new FavoriteFolder();
            favoriteFolder.setName(favoriteFolderAddDto.getName());
            favoriteFolder.setDescription(favoriteFolderAddDto.getDescription());
            favoriteFolder.setUserId(userId);
            favoriteFolderService.save(favoriteFolder);

            return ResponseEntity.ok("创建收藏夹成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("创建收藏夹失败！");
        }
    }

    @PostMapping("/delete/{favoriteFolderId}")
    public ResponseEntity<?> delete(@PathVariable Long favoriteFolderId,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);
            var favoriteFolder = favoriteFolderService.lambdaQuery()
                    .eq(FavoriteFolder::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(FavoriteFolder::getId, favoriteFolderId)
                    .select(FavoriteFolder::getUserId)
                    .one();

            if (favoriteFolder != null && userId.equals(favoriteFolder.getUserId())) {
                // 删除收藏夹
                favoriteFolderService.lambdaUpdate()
                        .set(FavoriteFolder::getIsDeleted, CommonConstants.DELETED_STATUS_YES)
                        .set(FavoriteFolder::getUpdatedAt, LocalDateTime.now())
                        .eq(FavoriteFolder::getId, favoriteFolderId)
                        .update();

                // 删除收藏夹中的所有收藏项
                folderBlogService.lambdaUpdate()
                        .set(FolderBlog::getIsDeleted, CommonConstants.DELETED_STATUS_YES)

                        .eq(FolderBlog::getFolderId, favoriteFolderId)
                        .update();
            } else {
                throw new RuntimeException("无权删除或收藏夹不存在");
            }
            return ResponseEntity.ok("删除收藏夹成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("删除收藏夹失败！");
        }
    }

    @GetMapping("/list")
    public ResponseEntity<?> list(@RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 获取用户的所有收藏夹
            var folders = favoriteFolderService.lambdaQuery()
                    .eq(FavoriteFolder::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(FavoriteFolder::getUserId, userId)
                    .list();

            // 获取每个收藏夹中的博客数量
            var folderIds = folders.stream().map(FavoriteFolder::getId).collect(Collectors.toList());
            var folderCounts = new java.util.HashMap<Long, Long>();

            if (!folderIds.isEmpty()) {
                // 使用list()获取分组统计结果
                var folderBlogCounts = new QueryWrapper<FolderBlog>()
                        .eq("is_deleted", CommonConstants.DELETED_STATUS_NO)
                        .in("folder_id", folderIds)
                        .select("folder_id", "COUNT(*) as count")
                        .groupBy("folder_id");

                List<Map<String, Object>> resultList = folderBlogService.listMaps(folderBlogCounts);

                resultList.forEach(item -> {
                    Long folderId = ((Number) item.get("folder_id")).longValue();
                    Long count = ((Number) item.get("count")).longValue();
                    folderCounts.put(folderId, count);
                });
            }

            // 组装预览数据
            var previewList = folders.stream().map(folder -> {
                var preview = new FavoriteFolderPreviewDto();
                preview.setId(folder.getId());
                preview.setName(folder.getName());
                preview.setDescription(folder.getDescription());
                preview.setBlogCount(folderCounts.getOrDefault(folder.getId(), 0L).intValue());
                preview.setCreatedAt(folder.getCreatedAt());
                return preview;
            }).collect(Collectors.toList());

            return ResponseEntity.ok(previewList);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("获取收藏夹列表失败！");
        }
    }

    @GetMapping("/detail/{favoriteFolderId}/{pageIndex}")
    public ResponseEntity<?> getDetail(@PathVariable Long favoriteFolderId,
            @PathVariable Integer pageIndex,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 获取收藏夹信息
            var folder = favoriteFolderService.lambdaQuery()
                    .eq(FavoriteFolder::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(FavoriteFolder::getId, favoriteFolderId)
                    .eq(FavoriteFolder::getUserId, userId)
                    .one();

            if (folder == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("收藏夹不存在！");
            }

            // 获取收藏夹中的博客ID列表
            var folderBlogs = folderBlogService.lambdaQuery()
                    .eq(FolderBlog::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(FolderBlog::getFolderId, favoriteFolderId)
                    .select(FolderBlog::getBlogId)
                    .list();

            var blogIds = folderBlogs.stream().map(FolderBlog::getBlogId).collect(Collectors.toList());
            List<BlogPreviewDto> blogPreviews = new ArrayList<>();

            if (!blogIds.isEmpty()) {
                // 获取博客信息（使用分页）
                var blogPage = blogService.lambdaQuery()
                        .eq(Blog::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                        .in(Blog::getId, blogIds)
                        .select(Blog::getId, Blog::getTitle, Blog::getSummary, Blog::getCreatedAt)
                        .page(new Page<>(pageIndex, CommonConstants.DEFAULT_PAGE_SIZE));

                // 组装博客预览数据
                blogPreviews = blogPage.getRecords().stream().map(blog -> {
                    var preview = BlogPreviewDto.builder().build();
                    preview.setId(blog.getId());
                    preview.setTitle(blog.getTitle());
                    preview.setSummary(blog.getSummary());
                    preview.setCreatedAt(blog.getCreatedAt());
                    return preview;
                }).collect(Collectors.toList());

                var pageResult = new PageResultDto<BlogPreviewDto>();
                pageResult.setContent(blogPreviews);
                pageResult.setTotalPages(blogPage.getPages());

                // 组装收藏夹详细信息
                var detail = new FavoriteFolderDetailDto();
                detail.setId(folder.getId());
                detail.setName(folder.getName());
                detail.setDescription(folder.getDescription());
                detail.setCreatedAt(folder.getCreatedAt());
                detail.setBlogPageResul(pageResult);

                return ResponseEntity.ok(detail);
            } else {
                var pageResult = new PageResultDto<BlogPreviewDto>();
                pageResult.setContent(new ArrayList<>());
                pageResult.setTotalPages(0L);

                // 如果没有博客，返回空的收藏夹信息
                var detail = new FavoriteFolderDetailDto();
                detail.setId(folder.getId());
                detail.setName(folder.getName());
                detail.setDescription(folder.getDescription());
                detail.setCreatedAt(folder.getCreatedAt());
                detail.setBlogPageResul(pageResult);

                return ResponseEntity.ok(detail);
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("获取收藏夹详情失败！");
        }
    }
}
